<?php

namespace addons\zzuser\controller\api;

use addons\zzuser\model\UserM;
use addons\zzuser\service\EncryptS;
use app\common\controller\Api;
use fast\Random;
use think\Validate;

class PasswordByOld extends Api
{
    protected $noNeedRight = 'index';

    public function index()
    {
        $validate = new Validate();
        if (!$validate->check(input(), [
            'password_old'     => 'require',
            'password_new'     => 'require',
            'password_confirm' => 'confirm:password_new',
        ])) {
            $this->error($validate->getError());
        }
        $password_old = input('password_old');
        $password_new = input('password_old');
        $user         = UserM::find($this->auth->id);
        if (!$user) {
            $this->error();
        }
        if (EncryptS::password($password_old, $user['salt']) != $user['password']) {
            $this->error('error password');
        }
        $salt = Random::alnum();
        $user->save([
            'salt'     => $salt,
            'password' => EncryptS::password($password_new, $salt),
        ]);
        $this->success();
    }
}
